package gl.java.network.transport.kcp.udp;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.internal.PlatformDependent;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class UdpServerChildHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
        log.info("UdpServerChildHandler.read0");
        ctx.fireChannelRead(msg);
    }

    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        DatagramPacket msg1 = null;
        try {
            msg1 = (DatagramPacket) msg;
            log.info("UdpServerChildHandler.channelRead1: {}", msg1.refCnt());
//        super.channelRead(ctx, msg);
            ctx.fireChannelRead(msg);
            log.info("UdpServerChildHandler.channelRead2: {} ", msg1.refCnt());

            log.info("------------------------------------------------------------------------");
        } catch (Exception e) {
            PlatformDependent.throwException(e);
        } finally {
            while (msg1 != null && msg1.refCnt() > 0) {
                msg1.release();
            }
        }


//        ctx.fireChannelReadComplete();
//        if (msg instanceof DatagramPacket) {
//            DatagramPacket msg1 = (DatagramPacket) msg;
//            log.info("msg.ref:{}", msg1.refCnt());
//        }
    }

    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        log.info("UdpServerChildHandler.channelReadComplete");
        super.channelReadComplete(ctx);
    }
}
